package com.surprise.biz.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import redis.clients.jedis.Jedis;

import com.google.common.collect.Lists;
import com.surprise.redis.LuaLoader;
import com.surprise.redis.RedisFactory;
import com.surprise.redis.RedisKeyGenerator;

/**
 * LayerGenerator.java
 * @author nick
 * @since 2015年5月5日
 */
@Component
public class LayerGenerator {
	@Autowired
	private RedisFactory redisFactory;
	@Autowired
	private LuaLoader luaLoader;
	
	/**
	 * redis中为每一个app增加一个hash
     * key: thread
     * value: 当前最大的layer
	 * @param thread
	 * @return
	 */
	public int genLayer(String thread) {
		Jedis jedis = null;
		try {
			jedis = redisFactory.getClient();
			return genLayer(jedis, thread);
		} finally {
			redisFactory.returnResource(jedis);
		}
	}
	
	public int genLayer(Jedis jedis, String thread) {
		String key = RedisKeyGenerator.commentHashLayer();
		String layer = (String)jedis.eval(luaLoader.getLua("layer"), Lists.newArrayList(key), Lists.newArrayList(thread));
		return Integer.valueOf(layer);
	}
	
	public int getLayer(String thread) {
		Jedis jedis = null;
		try {
			jedis = redisFactory.getClient();
			return getLayer(jedis, thread);
		} finally {
			redisFactory.returnResource(jedis);
		}
	}
	
	public int getLayer(Jedis jedis, String thread) {
		String key = RedisKeyGenerator.commentHashLayer();
		String layer = jedis.hget(key, thread);
		return layer == null ? 0 : Integer.valueOf(layer);
	}
}
